<template>
	<view>
		<view class="map_container">
			<view class="search">
				<u-search placeholder="请精确输入搜索内容" v-model="keyword" @custom="bindInput" @search="bindInput"
					@clear="clear"></u-search>
				<u-popup :show="show" mode="top" customStyle="positon:absolute;top:100rpx">
					<view class="content">
						<scroll-view scroll-y="true" style="">
							<view>
								<view v-for="(i ,index) in tips" :key="index"
									style="padding: 30rpx;border-bottom: .5px solid #E2E2E2" @click="goSearch(i)">
									{{i.name}}
								</view>
							</view>
						</scroll-view>
					</view>
				</u-popup>
			</view>

			<!-- <map id="myMap" class="map" style="width: 100%; height: 90%;" :latitude="latitude" :longitude="longitude"
				:markers="markers" show-location @poitap="poitap"></map> -->
			<div id="myMap" style="width: 100%; height: 90%;"></div>
			<!-- <div class="info">
			    <h4 id='status'></h4><hr>
			    <p id='result'></p><hr>
			    <p >由于众多浏览器已不再支持非安全域的定位请求，为保位成功率和精度，请升级您的站点到HTTPS。</p>
			</div> -->
		</view>
		<view class="location">
			<text class="local">{{local}}</text>
			<text class="distance" v-if="range!==''">(距离你{{range}})</text>
			<u-button text="确定" @click="goback()"></u-button>
		</view>
	</view>
</template>

<script>
	function bd_decrypt(bdLng, bdLat) {
	  const X_PI = Math.PI * 3000.0 / 180.0;
	  const x = bdLng - 0.0065;
	  const Y = bdLat - 0.006;
	  const Z = Math.sqrt(x * x + Y * Y) - 0.00002 * Math.sin(Y * X_PI);
	  const Theta = Math.atan2(Y, x) - 0.000003 * Math.cos(x * X_PI);
	  const lng = Z * Math.cos(Theta);
	  const lat = Z * Math.sin(Theta);
	  return {lng, lat};
	}
	import amapFile from "@/libs/amap-wx.130.js";
	var self, mapCtx
	export default {
		data() {
			return {
				// key: '0a7e3109fe2a9b39a5e2b854e164614f',
				latitude: '',
				longitude: '',
				firstlat: '',
				firstlng: '',
				local: '',
				distance: '',
				// 标记点
				markers: [],
				range: '',
				circles: [],
				radius: 0,
				amapObject: null,
				keyword: '',
				tips: [],
				show: false,
				map: null
			}
		},
		mounted() {
			this.loadScrpit()
		},
		methods: {
			getMapInfo(longitude, latitude) { //地址逆解析，写得波比肩膀酸
				let geocoder = new AMap.Geocoder({ //定义一个范围
					city: "全国", //城市设为北京，默认：“全国”
					radius: 300 //范围，默认：500
				});
				this.latitude = latitude
				this.longitude = longitude
				return new Promise((resolve, reject) => {
					geocoder.getAddress(`${longitude},${latitude}`, (status, res) => {
						console.log(status, res)
						if (status == 'complete') {
							let e = {
								address: res.regeocode.formattedAddress,
								latitude: latitude,
								longitude: longitude,
								classify: res.regeocode.addressComponent.province + '-' + res.regeocode
									.addressComponent.city + '-' +
									res.regeocode.addressComponent.district
							}
							resolve(e);
						}
					});
				})
			},
			async goback() {
				if (this.longitude == '') {
					uni.showToast({
						icon: 'none',
						title: '请允许定位'
					})
					return false
				}
				let res = await this.getMapInfo(this.longitude, this.latitude)
				// console.log(res)
				uni.$emit('map', res)
				uni.navigateBack({
					delta: 1
				})
			},
			panTo() { //指到所对应的地图点
				this.map.panTo([this.longitude, this.latitude]);
				//每次进入都清除添加的标记点
				this.map.remove(this.markers);
				//添加需要的标记点
				var marker = new AMap.Marker({
					map: this.map,
					position: [this.longitude, this.latitude]
				});
				this.markers.push(marker);
			},
			goSearch(e) {
				// console.log(e, '选择的地址')
				this.latitude = e.location.lat
				this.longitude = e.location.lng
				this.keyword = e.name
				this.local = e.name
				this.panTo()
				// this.map.setCenter(marker.getPosition());    
				this.show = false;
			},
			bindInput() {
				let that = this
				var keywords = this.keyword;
				// console.log(keywords)
				if (keywords == '') {
					return
				}
				AMap.plugin('AMap.Autocomplete', function() {
					// 实例化Autocomplete
					var autoOptions = {
						city: '全国'
					}
					var autoComplete = new AMap.Autocomplete(autoOptions);
					autoComplete.search(keywords, function(status, result) {
						// 搜索成功时，result即是对应的匹配数据
						// console.log(status, result, '搜索内容')
						if (status == 'complete') {
							let arr = result.tips.filter(item => {
								if (typeof item.location == "object") {
									return item
								}
							})
							that.tips = arr
							that.show = true;
						}
					})
				})
			},
			async showInfoClick(e) {
				// map.on('click', this.showInfoClick);
				let getLng = e.lnglat.getLng()
				let getLat = e.lnglat.getLat()
				let res = await this.getMapInfo(getLng, getLat)
				this.local = res.address
				this.panTo()
				// console.log(res, '地图点击事件')
			},
			loadScrpit() {
				let that = this
				//初始化地图对象，加载地图
				this.map = new AMap.Map('myMap', {
					resizeEnable: true,
					zoom: 13,
				});
				this.map.on('click', this.showInfoClick);
				var options = {
					'showButton': true, //是否显示定位按钮
					'position': 'LB', //定位按钮的位置
					/* LT LB RT RB */
					'offset': [10, 20], //定位按钮距离对应角落的距离
					'showMarker': true, //是否显示定位点
					'markerOptions': { //自定义定位点样式，同Marker的Options
						'offset': new AMap.Pixel(-18, -36),
						'content': '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
					},
					'showCircle': false, //是否显示定位精度圈
					'circleOptions': { //定位精度圈的样式
						'strokeColor': '#0093FF',
						'noSelect': true,
						'strokeOpacity': 0.5,
						'strokeWeight': 1,
						'fillColor': '#02B0FF',
						'fillOpacity': 0.25
					}
				}
				AMap.plugin(["AMap.Geolocation"], () => {
					var geolocation = new AMap.Geolocation(options);
					this.map.addControl(geolocation);
					geolocation.getCurrentPosition()
					AMap.event.addListener(geolocation, 'complete', onComplete)
					AMap.event.addListener(geolocation, 'error', onError)

					function onComplete(data) {
						console.log(data, '定位成功')
						// this.$vconsole(data,'定位成功')
						that.local = data.formattedAddress
						that.latitude = data.position.lat
						that.longitude = data.position.lng
						// console.log(that.longitude, that.latitude, that.local)
						// data是具体的定位信息
					}

					function onError(data) {
						 // AMap.plugin('AMap.CitySearch', function () {
						 //   var citySearch = new AMap.CitySearch()
						 //   citySearch.getLocalCity(function (status, result) {
						 //     if (status === 'complete' && result.info === 'OK') {
							// 	 console.log(result)
						 //       // 查询成功，result即为当前所在城市信息
						 //     }
						 //   })
						 // })
						console.log(data, '定位失败')
						that.lib_getPosition() //傻逼高德地图不能在谷歌中使用高精度定位，此时只能百度定位,但是又太慢了,我也很无赖
						// 定位出错
					}
				});
			},
			/**
			 * 百度地图获取经纬度
			 */
			 lib_getPosition() {
				const that = this;
				const BMapGeolocation = new BMapGL.Geolocation();;
				BMapGeolocation.getCurrentPosition(async (r) => {
					if (r.latitude && r.longitude) {
						console.log("baidu");
						// 获取到经纬度（百度转换高德经纬度）
						const {
							lng,
							lat
						} = bd_decrypt(r.longitude, r.latitude);
						// console.log(lng,lat)
						let res = await that.getMapInfo(lng, lat)
						that.local = res.address
						that.panTo()
						// that.center = [lng, lat];
						// 根据经纬度获取当前经纬度的位置信息
						// that.getAdd();
					} else {
						// console.log(22);
					}
				});
			},
			/**
			 * 根据经纬度获取地址
			 */
			getAdd() {
				const that = this;
				const geocoder = new AMap.Geocoder({
					radius: 1000,
					extensions: "all",
				});
				const [lng, lat] = this.center;
				geocoder.getAddress([lng, lat], function(status, result) {
					if (status === "complete" && result.info === "OK") {
						console.log(result, "result");
						if (result && result.regeocode) {
							console.log(
								`result.regeocode.formattedAddress:`,
								result.regeocode.formattedAddress
							);
							// 获取到定位信息的处理逻辑
							// ...
						}
					}
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.map_container {
		width: 100%;
		overflow: hidden;
		position: absolute;
		top: 0;
		bottom: 80px;
		left: 0;
		right: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.search {
			width: 90%;
			padding-bottom: 15rpx;
		}

		.map {
			height: auto;
			width: 100%;
		}
	}

	.location {
		width: 100%;
		height: auto;
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0px;
		// height: 80px;
		background: #fff;
		padding: 2.5%;
		overflow: hidden;
		z-index: 1000000;
		font-size: 24rpx;

		.distance {
			color: #4295FA;
			font-size: 12px;
		}
	}
</style>
